/**
 * 
 */
package com.desksoft.ecommerce.util.transfer;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.desksoft.ecommerce.constants.Constants;
import com.desksoft.ecommerce.util.remoteio.RemoteIOFactory;
import com.desksoft.ecommerce.util.remoteio.RemoteIOSetting;
import com.desksoft.ecommerce.util.remoteio.RemoteIOUtil;
import com.desksoft.utility.string.StringUtil;

/***************************************
 * <pre>
 * 版权所有：杭州迪科软件 保留所有权利
 * 创建日期: Jun 20, 2012
 * 创建作者：yejw
 * 文件名称：DefaultTransfer.java
 * 版本：1.0
 * 功能：
 * 最后修改时间：Jun 20, 2012
 * 修改记录：
 * </pre>
 *****************************************/
public class DefaultTransfer implements ITransfer {
	
	/**
	 * 
	 */
	private RemoteIOUtil remoteIO;
	private RemoteIOSetting servInfo;
	
	public DefaultTransfer(RemoteIOSetting settings) {
		this.remoteIO = RemoteIOFactory.getInstance(settings);
		this.servInfo = settings;
	}
	
	/**
	 * 
	 */

	/* (non-Javadoc)
	 * @see com.desksoft.mall.structure.htmlgen.transfer.ITransfer#transfer(java.lang.String, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Boolean transfer(String targetPath, String data) throws IOException {
		OutputStream output = remoteIO.getOutputStream(targetPathCheck(targetPath));
		IOUtils.write(checkNotNull(data), output, Constants.UTF8);
		
		return Boolean.TRUE;
	}
	
	/* (non-Javadoc)
	 * @see com.desksoft.ecommerce.util.transfer.ITransfer#transfer(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String transfer(String targetPath) throws IOException {
		InputStream input = remoteIO.getInputStream(targetPath);
		return IOUtils.toString(input, Constants.UTF8);
	}
	
	/* (non-Javadoc)
	 * @see com.desksoft.mall.structure.htmlgen.transfer.ITransfer#disconnect()
	 */
	@Override
	public void disconnect() {
		this.remoteIO.disconnect();
	}

	/* (non-Javadoc)
	 * @see com.desksoft.ecommerce.util.transfer.ITransfer#getServInfo()
	 */
	@Override
	public RemoteIOSetting getServInfo() {
		return this.servInfo;
	}

	/**
	 * @param targetPath
	 * @throws IOException 
	 */
	private String targetPathCheck(String targetPath) throws IOException {
		String split = "/";
		String subpath = null;
		
		String[] subpaths = StringUtil.splitter(split, 
				StringUtils.substringBeforeLast(checkNotNull(targetPath), split));
		
		for (String path : subpaths) {
			subpath = ((subpath == null) ? path : (StringUtil.join(subpath, split, path)));
			if (remoteIO.exists(subpath)) {
				continue;
			}
			
			remoteIO.mkDir(subpath);
		}
		
		return targetPath;
	}

}
